var PageContainer = new Class({
    Implements:[Events,Options]
    ,name:"PageContainer"
    ,widgetFactory: new WidgetFactory()
    ,redirect:null
    ,mask:null
    ,initData:null
    ,cacheData:null
    ,calendar:null
    ,select:null
    ,uploadCommit:null
    ,edit:false
    ,editor :null
    ,pinitData:null
    ,studioComm:null
    ,isEdit:function() {
        return this.edit;
    }
    ,initialize: function(edit) {
        this.edit = edit;
    }
    ,initSwordTag :function(node) {
        var swordWidgets = [];
        if($defined(node)) {
            swordWidgets = $(node).getElements("div[sword][sword!='PageInit'][sword!='SwordCacheData']");
        } else {
            swordWidgets = $$("div[sword][sword!='PageInit'][sword!='SwordCacheData']");
        }
        var newSwordWidgets = [];
        swordWidgets.each(function(item, index) {
            if(item.getAttribute('lazy') != 'true') {
                newSwordWidgets.include(item);
                item.set('isload', 'true');
            }
        }.bind(this));
        swordWidgets = newSwordWidgets;
        if(this.isEdit()) {
            this.getEditor().start();
        }
        var u = this;
        swordWidgets.each(function(value,i) {
            if(this.isEdit()) {
                this.getEditor().dealEl(value);
            }
            if(value.get('sword')=="SwordCollapse"|| value.get('sword')=="SwordToolBar"){
            	this.WidgetArry.push(value);
            }else{
            	this.initParamOne(value);
            }
            if(swordWidgets.length-1==i){
            	this.WidgetArry.each(function (n){
            		u.initParamOne(n);
            	});
            }
        }, this);
    }
    ,WidgetArry:[]
    ,initParamOne:function(node){
    	var swordWidget = this.widgetFactory.create(node);
    	node.pNode = node;
//        this.widgets.set(node.get('name'), swordWidget);
        this.setWidget(node.get('name'),swordWidget,node.get('dataName'));
        swordWidget.initParam(node);
    }
    ,initSwordPageData:function() {
        if($defined($('SwordPageData'))) {
            var d = $('SwordPageData').get('data');
            if($chk(d)) {
                pc.initData = JSON.decode(d.replace(/&apos;/g, "'"));
            }
        } else {
            var pi = this.getPageInit();
            if(pi) {
                pi.initStaticData();
            }
        }
    }
    ,getAttrFunc:function(key) {
        for(var i = 0; i < (this.data || []).length; i++) {
            var d = this.data[i];
            if(d["name"] == key) {
                return d["value"];
            }
        }
    }
    ,getDataFunc4Name:function(key) {
    	return this.data.filter(function(item){return item["name"]==key;})[0];
    }
    ,getDataFunc4DataName:function(key) {
    	return this.data.filter(function(item){return item["dataname"]==key||item["dataName"]==key;})[0];
    }
    ,initPageData:function() {
        var pi = this.getPageInit();
        if($defined($('SwordPageData'))) {
            if($chk(this.initData)) {
                var param = {'dataObj':this.initData };
                if(pi) {
                    $extend(param, {
                        'onSuccess':this.getFunc(pi.options.onSuccess)[0]
                        ,'onError':this.getFunc(pi.options.onError)[0]
                        ,'onFinish':this.getFunc(pi.options.onFinish)[0]
                        ,'onAfterLoadData':this.getFunc(pi.options.onAfterLoadData)[0]
                    });
                }
                param.initpage=true;
                pc.loadData(param);
            }
        } else {
            if(pi) {
                pi.getInitData({
                    'onSuccess':this.getFunc(pi.options.onSuccess)[0]
                    ,'onError':this.getFunc(pi.options.onError)[0]
                    ,'onFinish':this.getFunc(pi.options.onFinish)[0]
                    ,'onAfterLoadData':this.getFunc(pi.options.onAfterLoadData)[0]
                });
            }
        }
    }
    ,initPublicTag:function() {
        this.redirect = this.widgetFactory.create("Redirect");
    }
   /* ,initPageDataRedirectFormLast:function() {
        var param1 = {'dataObj':this.pinitData };
        var pi = this.getPageInit();
        $extend(param1, {
            'onSuccess':this.getFunc(pi.options.onSuccess)[0]
            ,'onError':this.getFunc(pi.options.onError)[0]
            ,'onFinish':this.getFunc(pi.options.onFinish)[0]
        });
        param1.initpage=true;
        this.loadData(param1);
    }*/
    ,initCoutTag:function() {
        var couts = $$("*[tag='cout'][name]");
        couts.each(function(el) {
            var val = this.getInitData(el.get('name'));
            if(!$chk(val))return;
            val = val.value;
            el.set('text', val);
        }, this);
    }
    /*,initPageDataRedirectFormLastBefore:function() {
        var pData,ppr = parent.pc.redirect;
        if(ppr.options.items.length == 2) {
            pData = ppr.getData();
        } else if(ppr.options.items.length > 2) {
            var length = ppr.options.items.length;
            var lastFramePage = ppr.options.items[length - 2].page;
            var lastFrame = $(parent.document.body).getElement('iframe[ifname=RedirectIframe_' + lastFramePage + ']').contentWindow;
            pData = lastFrame.pc.redirect.getData();
        }
        this.pinitData = pData;
        this.initData = pData;
    }*/
//    ,
//    swordCacheArray:[]//存储页面缓存的定义
//    ,
//    initSwordCacheData:function(){// 读取页面定义的缓存
//        var ct = $('SwordCacheData');
//        var querystr = null;
//        if($defined(ct)){//由于历史原因，下拉树和下拉列表分开定义
//            querystr = ct.get('queryTree');
//            if(querystr){
//                this.swordCacheArray.combine(JSON.decode(querystr));
//            }
//            querystr = ct.get('query');
//            if(querystr){
//                this.swordCacheArray.combine(JSON.decode(querystr));
//            }
//        }
//    }
    ,process:function() {
        this.initPublicTag();
        this.initSwordPageData();
        if(jsR.config.SwordClientCache)this.initSwordCacheData();
        //todo 如果是不同的域,会报拒绝访问的错误，所以加上try{}catch(e){},应该会有更合理的判断方式
       /* try {
            if(parent && parent.jsR && window.frameElement && window.frameElement.name && window.frameElement.name.contains('RedirectIframe_')) {
                this.initPageDataRedirectFormLastBefore();
            }
        } catch(e) {
        }*/
        this.firePIOnBefore();
        this.initSwordTag();
        this.firePIOnDataInit();
        //todo 如果是不同的域,会报拒绝访问的错误，所以加上try{}catch(e){},应该会有更合理的判断方式
       /* try {
            if(parent && parent.jsR && window.frameElement && window.frameElement.name && window.frameElement.name.contains('RedirectIframe_')) {
                this.initPageDataRedirectFormLast();
            } else {
                this.initPageData();
            }
        } catch(e) {
            this.initPageData();
        }*/
        this.initPageData();
        this.firePIOnAfter();
    }
    ,firePIOnDataInit:function() {
        var pi = this.getPageInit();
        if(pi) {
            pi.fireEvent('onDataInit');
        }
    }
    ,firePIOnAfter:function() {
        var pi = this.getPageInit();
        if(pi) {
            pi.fireEvent('onAfter',pc.initData);
        }

        var afters = jsR.config.onAfter;
        if ($type(afters) == 'array') {
            afters.each(function(ev) {
                try {
                    eval(ev.replace('()', ''));
                } catch(e) {
                    //  alert('出错说明没有定义这个方法');
                    return;//出错说明没有定义这个方法。。。
                }
                var f = pi.getFunc(ev)[0];
                f();
            });
        }

    }
    ,firePIOnBefore:function() {
        var pi = this.getPageInit();
        if(pi) {

            var befores = jsR.config.onBefore;
            if($type(befores) == 'array') {
                befores.each(function(ev) {
                    try {
                        eval(ev.replace('()', ''));
                    } catch(e) {
                        //                        alert('出错说明没有定义这个方法');
                        return;//出错说明没有定义这个方法。。。
                    }
                    var f = pi.getFunc(ev)[0];
                    f();
                });
            }

            pi.fireEvent('onBefore',pc.initData);

        }
    }
   
    ,getMask:function() {
        if(!$defined(this.mask))this.mask = this.widgetFactory.create("SwordMask");
        return this.mask;
    }
    ,getUploadCommit:function() {
        if(!$defined(this.uploadCommit))this.uploadCommit = this.widgetFactory.create("SwordFileUpload");
        return this.uploadCommit;
    }
    ,getCalendar:function() {
        if(!$defined(this.calendar))this.calendar = this.widgetFactory.create("SwordCalendar");
        return this.calendar;
    }
    ,getCalendar4grid:function() {
        if(!$defined(this.calendar4grid))this.calendar4grid = this.widgetFactory.create("SwordCalendar");
        return this.calendar4grid;
    }
    ,getSelect:function() {
        if(!$defined(this.select))this.select = this.widgetFactory.create("SwordSelect");
        return this.select;
    }
    ,getSelect4grid:function() {
        if(!$defined(this.select4grid))this.select4grid = this.widgetFactory.create("SwordSelect");
        return this.select4grid;
    }
    ,getValidate:function() {
        if(!$defined(this.validate))this.validate = this.widgetFactory.create("SwordValidator");
        return this.validate;
    }
    ,getEditor:function() {
        if(!$defined(this.editor))this.editor = this.widgetFactory.create("Editor");
        return this.editor;
    }
    ,getValidateCode:function() {
        if(!$defined(this.validateCode))this.validateCode = this.widgetFactory.create("SwordValidateCode");
        return this.validateCode;
    }
    ,getPageInit:function() {
        if(!$defined(this.pageInit)) {
            var pageInits = $$("div[sword='PageInit']");
            if(pageInits.length > 1) {
                throw new Error('一个页面只能设置一个初始数据操作！');
            } else if(pageInits.length == 1) {
                this.pageInit = this.widgetFactory.create("PageInit");
                this.pageInit.initParam(pageInits[0]);
            } else if(pageInits.length == 0) {
                this.pageInit = this.widgetFactory.create("PageInit");
            }
        }
        return this.pageInit;
    }
    ,getDownLoadForm:function() {
        if(!this.downLoadForm) {
            var iframeId = "swordDownLoadIframe";
            this.downLoadForm = new Element('form', {
                'name':"swordDownLoadForm",
                'method':'post',
                'target':iframeId,
                'action':'download.sword',
                styles:{'display':'none'}
            }).inject($(document.body));
            new Element('iframe', {
                id:iframeId,
                name:iframeId,
                styles:{'display':'none'}
            }).inject($(document.body));
            this.downLoadForm.postReqInput = new Element('input', {
                'name':"postData"
            }).inject(this.downLoadForm);
        }
        return this.downLoadForm;
    }
    ,submit:function() {
        if(arguments.length != 1)return;
        var name = arguments[0]['widgets'][0];
        var widget = this.getWidget(name);
        if(!widget.validate())return;
        var req = {
            'ctrl':arguments[0].ctrl || ''
            ,'tid':arguments[0].tid || ''
            ,'data':widget.getSubmitData()
        };
        var myRequest = new Request({
            method: 'post',
            async : true,
            url: 'ajax.sword'
        });
        myRequest.onSuccess = function(responseText) {
//            logger.debug('返回数据=' + responseText, 'pc');
            if(!$chk(responseText)) {
//                logger.debug('没有返回数据', 'pc');
                return;
            }
            var jsonObj = JSON.decode(responseText);
            this.loadData({'dataObj':jsonObj});
        }.bind(this);
        myRequest.onFailure = function() {
            this.alertError('提交数据出错了。。。pc.submit');
        }.bind(this);
        myRequest.send('postData=' + JSON.encode(req));
    },
    create:function(widget) {
        return this.widgetFactory.create(widget);
    }
    ,loadData:function(param) {
        var dataObj = param['dataObj'];
        var onError = param['onError'];
        var onSuccess = param['onSuccess'];
        var loaddata = param['loaddata'];
        if(!$chk(dataObj)) {
            if($defined(param['onFinish'])) {
                param['onFinish'](dataObj);
            }
            return;
        }
//        logger.debug("装载数据开始。。。。。", 'PageContainer');
        if(!$defined(dataObj.getAttr)) {
            dataObj["getAttr"] = this.getAttrFunc;
        }
        if(!$defined(dataObj.getData)) {
            dataObj["getData"] = this.getDataFunc4Name;
        }
        if(!$defined(dataObj.getDataByDataName)) {
            dataObj["getDataByDataName"] = this.getDataFunc4DataName;
        }
        if(dataObj['exception']) {
            if($defined(onError)) {
                onError(dataObj);
            }

            if (param['errMes']!=false) {

                if(dataObj['ajaxErrorPage']) {
                    if(!dataObj['exceptionMes'])dataObj['exceptionMes']='';
                    var popupParam = JSON.decode(dataObj['ajaxErrorPopupParam'].replace(/&apos;/g, "'")) || {titleName:'出错了！',width: 412,height:450};
                    popupParam['param'] = {'win':window,'data':dataObj};
                    swordAlertIframe(jsR.rootPath + 'sword?ctrl=SwordPage_redirect&pagename=' + dataObj['ajaxErrorPage'], popupParam,null);
                }
                else {
                    this.alertError('<b><font color="red">出错了！</font></b>' 
                    	/*+ '<br><font color="blue" >错误名称</font> : ' + dataObj['exceptionName']*/
                        + '  <br><font color="blue" >错误信息</font> : ' + dataObj['exceptionMes']
                        /*+ '<br><font color="blue" >调试信息</font> : ' + dataObj['debugMes']*/);
                }

            }
            pc.getMask().unmask();
            return;
        } else {

            var resMsg = dataObj['message'];
            if($defined(resMsg)) {
                if(resMsg == "SWORD_TIME_OUT") {
                    _TIMEOUT();
                } else {
                    //var len = resMsg.length;
                    //var height = Math.ceil(len / 14) * 16;
                    //h = height + 'px';
                    swordAlert(resMsg);
                }
            }
            if($defined(onSuccess)) {
                onSuccess(dataObj);
                if(!document.body) {
                    return;
                }
            }
        }
        if($defined(param['onFinish'])) {
            param['onFinish'](dataObj);
        }
        /*if(!$defined(param['redirect']) || param['redirect'] != false) {
            if($chk(dataObj.page)) {
                var page = dataObj.page;
//                logger.debug('执行页面跳转开始，目标页：' + page);
                dataObj.page = null;
                this.redirect.setData(dataObj);
                if(page.lastIndexOf('?') != -1) {
                    page += "&";
                } else {
                    page += "?";
                }
                page += "r=" + Math.random();
                if(Browser.Engine.gecko) {
                    this.redirect.go.delay(1, this.redirect, [page]);
                } else {
                    this.redirect.go(page);
                }
                return;
            }
        }*/
        if(loaddata == 'widget') {
        	//全局的loaddata == 'widget',容器将不负责数据初始化操作
            return;
        }
        var data = dataObj['data'];
        if($chk(!data)) {
        	//返回的数据中没有res->data属性，不进行数据装载操作。。。"
            return;
        }
        data.each(function(widgetData) {
		     if(!$chk(widgetData['dataName'])){
		          this.dealWidgetName(widgetData,param);
		      }
        }, this);
        data.each(function(widgetData) {
            if(widgetData['dataName']){//处理dataname
            	this.dealDataName(widgetData,dataObj,param);
            }
        }, this);
		
        this.initCoutTag();

        if($defined(param['onAfterLoadData'])) {
            param['onAfterLoadData'](dataObj);
        }
    }
    
    ,dealDataName:function(widgetData,dataObj,param){
    	if(widgetData['loaddata'] != 'widget') {
    		var dn=widgetData['dataName'];
    		if(param.initpage!=true){ //不是页面初始化操作，select自动重载数据
    			//装载下拉的数据，注意：这里没有区分是否是下拉类型，可能会有问题
        		this.reloadSel(dn,dataObj);
    		}
    		 
    		if(this.getWidgetsByDataname(dn)){
    			widgetData.initpage=param.initpage;//通知各个组件是否为第一次初始化数据
    			this.getWidgetsByDataname(dn).initData(widgetData);
    		}
    		
    	}
    }
    ,dealWidgetName:function(widgetData,param){
    	var widgetName = widgetData['name'];
        if(!$chk(widgetName)) {
        	//res->data->widget中没有name属性，略过此段数据。。。
            return;
        }
//        if(!widgetName.contains('.') && this.getWidget4loaddata(widgetName) == null) {
        if(!widgetName.contains('.') && this.getWidget(widgetName) == null) {
        	//组件池中没有组件【" + widgetName + "】，不执行装载数据
            return;
        }
        if(widgetData['loaddata'] != 'widget') {
//        	 this.getWidget4loaddata(widgetName).initData(widgetData);
        	 widgetData.initpage=param.initpage;//通知各个组件是否为第一次初始化数据
        	 this.getWidget(widgetName).initData(widgetData);
        }
    }
    
    ,widgets:new Hash()
    ,widgets_dataname:new Hash() //按dataname存放组件对象
    ,setWidget:function(key, widget,dataname) {
        this.widgets.set(key, widget);
        if(dataname){
        	if(!this.widgets_dataname.get(dataname)){
        		var a=[];
        		a.initData=function(d){
                    a.each(function(obj){
                       if(obj)obj.initData(d);
                    });
                } ;
                this.widgets_dataname.set(dataname,a);
            }
        	this.widgets_dataname.get(dataname).erase(widget);
            this.widgets_dataname.get(dataname).push(widget);
        }
    }
    ,getWidget:function(key) {
        return this.widgets.get(key);
    }
    ,getWidgetsByType:function(type) {
        return this.widgets.filter(function(value, key) {
        	 return $type(value) == type;
        });
    }
    ,getWidgetsByDataname:function(dataname){
        return this.widgets_dataname.get(dataname);
    }
    
      
    
    
    /* ,widgets_loaddataOnly:new Hash()     //保存对象，这些对象在loaddata的时候会被调用，在$w的时候获取不到，hash中value是数组。目前：pulltree
    ,setWidget4loaddata:function(key,obj){
        if(!this.widgets_loaddataOnly.get(key)){
            this.widgets_loaddataOnly.set(key,[]);
        }
        this.widgets_loaddataOnly.get(key).push(obj);
    }
    ,getWidget4loaddata:function(name){
         if(this.widgets_loaddataOnly.get(name)){
             var r=[];
             r.initData=function(d){
                 r.each(function(obj){
                    if(obj)obj.initData(d);
                 });
             } ;
             return r.include(this.getWidget(name)).extend(this.widgets_loaddataOnly.get(name));
         }else{
             return this.getWidget(name);
         }
    }*/
    
   
    
    ,getResData:function(name, dataObj, flag,init) {
        if(!$chk(flag)) {
            flag = 'name';
        }
        if($chk(!dataObj)) {
//            logger.debug("没有获得有效数据res", 'PageContainer');
            return;
        }
        var data = dataObj['data'];
        if($chk(!data)) {
//            logger.debug("返回的数据中没有res->data属性", 'PageContainer');
            return;
        }
        var temp;
        data.each(function(widgetData) {
            var widgetName = widgetData[flag];
            if($chk(!widgetName)) {
//                logger.debug("res->data->widget中没有" + flag + "属性，略过此段数据。。。", 'PageContainer');
                return;
            }
            if(name == widgetName) {
            	if($defined(init)){
            		if($defined(widgetData[init])){
            			temp = widgetData;
            		}
            	}else {
            		temp = widgetData;
            	}
            }
        }, this);
        return temp;
    }
    ,downLoad:function(req) {
        var form = this.getDownLoadForm().set({'target':'swordDownLoadIframe','action':'download.sword'});
        form.postReqInput.set('value', JSON.encode(req));
        form.submit();
    }
    //form的方式提交
    ,SwordformSubmit:function(req, target) {
        var url = "form.sword";
        var form = this.getDownLoadForm().set({'target':target,action:url});
        form.postReqInput.set('value', JSON.encode(req));
        form.submit();
    }
    
    ,form_back:function(param){
    	this.scY = document.documentElement.scrollTop;
    	this.redirect.hidePEl();
		var fromEl=this.getSaveStateForm();
        fromEl.postReqInput.set('value', JSON.encode(param['req']));
        setTimeout(function(){fromEl.submit();},1);//此处解决ie进度条加载的问题
    },form_open:function(param){
    	var options = param['openOptions'];
    	options = JSON.decode(options);
    	var tid = param['tid'];
    	var swordPopUpBox = _getTopSwordPopUpBox();
    	var ifs = swordPopUpBox.alertIframe($extend({message :tid}, options));
    	var ifn = ifs.frames.name;
    	this.SwordformSubmit(param['req'],ifn);
    }
    /*
     统一提交数据接口
     req: 必填, 需要单独提交的数据
     onSuccess ：选填， 后台成功，没有异常的回调
     onError ： 选填，后台发生了异常
     async：选填，true false 默认为true 异步
     loaddata:选填，是否为组件装载数据，widget container 默认为container
     onFinish:选填，不管出错还是成功执行，都会执行此方法。
     errMes : 选填，当后台出现异常的时候，是否alert错误信息， 默认为 true  ，关闭为 false
     redirect：选填，是否根据返回数据的page属性自动跳转页面
     postType(type) :选填， ajax form (form_target,支持target) download  提交类型 ， 默认为ajax提交   ,当download的时候其余的参数将失效
     */
    ,postReq:function(param) {
    	var postType=param['postType'];
    	if(postType=="form_back"){
    		this.form_back(param);
    		return;
    	}
    	if(postType=="form_open"){
    		this.form_open(param);
    		return;
    	}
    	if($defined(postType) && postType.contains("form")) {
            var target = "";
            if(postType.contains("form_")) {
                target = postType.split("_")[1];
            }
//            logger.debug('使用form方式提交...target方式为' + target, 'PageContainer', 'postReq');
            this.SwordformSubmit(param['req'], target);
            return;
        }
        if(postType == 'download') {
//            logger.debug('使用文件下载的方式提交数据。。。', 'PageContainer', 'postReq');
            this.downLoad(param['req']);
            if($defined(param.onFinish)) {
                param.onFinish();
            }
            return;
        }
        var async = true;
        var errMes = true;
        if(param['async'] =='false'|| param['async'] == false) {
            async = false;
        }
        if($defined(param['errMes']) && param['errMes'] == false) {
            errMes = false;
        }
        param['errMes'] = errMes;
        var req = param['req'];
        var onSuccess = param['onSuccess'];
        var onError = param['onError'];
        var loaddata = param['loaddata'];
        var myRequest = new Request({
            method: 'post',
            async : async,
            url: 'ajax.sword?r=' + Math.random()
        });
        myRequest.onSuccess = function(responseText) {
//            logger.debug('获得返回数据=' + responseText, 'PageContainer', 'postReq');
            if(!$chk(responseText)) {
//                logger.debug('没有获得有效返回数据！', 'PageContainer', 'postReq');
                return;
            }
            param['dataObj'] = JSON.decode(responseText);
            this.loadData(param);
        }.bind(this);
        myRequest.onFailure = function() {
        	var rText=this.xhr.responseText;
        	if(jsR.server()&&$chk(rText)){
        		swordAlert(this.xhr.responseText,{width:860});
        	    sowrdMaskResize();//重新定位下弹出框位置.
        	}else if(rText==""&&this.xhr.status==0) {
        		alert("与服务器连接断开，请尝试重新登录或与管理员联系!");
        	}
        	pc.getMask().unmask();
        };
        var postData = "";
        postData = JSON.encode(req);
        postData = postData.replace(/&/g, "#*^@^*#");
        postData = postData.replace(/%/g, "%25");
        postData = postData.replace(/[+]+/g, '%2B');
        if(param['encodeData'] && param['encodeData'] == "true") {
            postData = encodeURI(postData);
        }else if(swordCfg.postReq&&swordCfg.postReq.encodeData){
            postData = encodeURI(postData);
        }

//        logger.debug('开始提交数据=' + postData, 'PageContainer', 'postReq');
        try {
            myRequest.send('postData=' + postData);
        } catch(e) {
            if(jsR.server())alert("与服务器连接断开，请尝试重新登录或与管理员联系!");
            pc.getMask().unmask();
            throw e;
        }
    }
    ,getSaveStateForm:function() {
        if (!this.stateForm) {
            var iframeId = "swordStateFormIframe"+Math.random();
            //this.statueids.push(iframeId);
            this.stateForm = new Element('form', {
                'name':"swordStateForm",
                'method':'post',
                'target':iframeId,
                'action':'form.sword',
                styles:{'display':'none'}
            }).inject($(document.body));
            var iframeEl=new Element('iframe', {
                myid:"swordStateFormIframe",
                name:iframeId,	
                frameborder:"no", 
                styles:{
                	border: '0 none',
                    height: '100%',
                    'overflow-x': 'hidden',
                    'overflow-y': 'auto',
                    width: '100%'
                }
            	,src:""
            });iframeEl.inject($(document.body));
            if(Browser.Engine.trident) { //if  IE
            	iframeEl.addEvent('readystatechange', function(){
                    if (iframeEl.readyState == "complete"){
                    	$((this.contentDocument||this.contentWindow.document).body).setStyle("padding","0");
                    }
                });
         	} else {
         		iframeEl.addEvent('load', function(){
         			$(this.contentDocument.body).setStyle("padding","0");
                });
            } 	
            this.stateForm.postReqInput = new Element('input', {
                'name':"postData"
            }).inject(this.stateForm);
        }
        return this.stateForm;
    }
    ,getReq:function(obj) {
        var result = {
            'tid':obj.tid
            ,'ctrl':obj.ctrl
            ,'page':obj.page
            ,'data':obj.widgets
        };
        var data = [];
        if($chk(obj.data)) {
            var params = obj.data.split('&');
            params.each(function(param) {
                var tmp = param.split('=');
                var attr = {
                    "sword": "attr",
                    "name": tmp[0],
                    "value": tmp[1]
                };
                data[data.length] = attr;
            });
        }
        if(!$chk(result.data)) {
            result.data = data;
        } else {
            result.data.extend(data);
        }
        return result;
    }
    ,getInitData:function(widgetName) {
        if($chk(widgetName)) {
            return this.getResData(widgetName, this.initData);
        } else {
            if(!$defined(this.initData))this.initData = [];
            if(!$defined(this.initData.getAttr)) {
                this.initData["getAttr"] = this.getAttrFunc;
            }
            return this.initData;
        }
    }
    ,getInitDataByDataName:function(dataName,type,tag) {
    	if(!$defined(type)){
    		type="dataName";
    	}
        return this.getResData(dataName, this.initData, type,tag);
    }
    ,
    /**
     * 根据组件标识删除数据
     * 成功，返回true
     * 失败，返回false
     */
    deleteDataByWidgetName:function(widgetName) {
        return this.deleteData(widgetName, this.initData);
    },
    /**
     * 根据组件的dataname删除数据
     * 成功，返回true
     * 失败，返回false
     */
    deleteDataByDataName:function(dataName) {
        return this.deleteData(dataName, this.initData, 'dataName');
    }
    ,deleteData:function(name, dataObj, flag) {
        if(!$chk(flag)) {
            flag = 'name';
        }
        if($chk(!dataObj)) {
//            logger.debug("没有获得有效数据res", 'PageContainer');
            return false;
        }
        var data = dataObj['data'];
        if($chk(!data)) {
//            logger.debug("返回的数据中没有res->data属性", 'PageContainer');
            return false;
        }
        data.each(function(widgetData, index) {
        	if(widgetData){
	            var widgetName = widgetData[flag];
	            if($chk(!widgetName)) {
	//                logger.debug("res->data->widget中没有" + flag + "属性，略过此段数据。。。", 'PageContainer');
	                return false;
	            }
	            if(name == widgetName) {
	                data.splice(index,1);//删除当前项
	                return true;
	            }
        	}
        }, this);
    }
    ,alert:function(mes) {
        swordAlert(mes);
    }
    ,alertError:function(mes) {
    	swordAlert(mes, {'width':480,'height':200});
    }
    ,getStudioComm:function() {
        if(!$defined(this.studioComm))this.studioComm = this.widgetFactory.create("StudioComm");
        return this.studioComm;
    }

    //根据dataname 重新装载下拉列表数据
    ,reloadSel:function(dataname, resdata) {
        this.deleteDataByDataName(dataname);
        var data = this.getResData(dataname, resdata, 'dataName');
        if(!data)return;
        if(! pc.initData){
            pc.initData = {data:[]};
        }
        this.initData.data[this.initData.data.length] = data;
    },
    /**以下为前台缓存
     */
    initSwordCacheData:function(){
    	var ct = $$("div[sword='SwordCacheData']");
    	if(ct.length==0)return;
    	ct = ct[0];
    	var qs = ct.get('query');
        if(qs){
    		var qo = JSON.decode(qs);		
    		var paramarr = $H();
    		//循环页面定义标签 ，批量进行版本比较、加载缓存数据
    		qo.each(function(q,index){
    				var sql = "";
    				if(q.W){
    					sql = ("SELECT T.* FROM {T} AS T WHERE "+q.W).substitute(q);
    				}
    				paramarr.set(q.T,sql);
    		});
    		$cache.batchget(paramarr,function(result){
    			 result.forEach(function(v,k){
    				 var tempdata = $H({"data":[{"data":v,cacheName:k,init:"true"}]});
    			    	if(!$chk(pc.initData)){
    			    		pc.initData = tempdata;
    			    	}else{
    			    		pc.initData.data.extend(tempdata.data);
    			    	}
    			 });			
    		});
        }
    }
    ,selectDataFilter:function(sqlObj, backFunc) {
    	if($chk(sqlObj)) {
    		var sql = "";
    		var table = sqlObj.T;
    		if(sqlObj.W) {
    			sql += "SELECT T.* FROM " + table + " AS T WHERE "+sqlObj.W;
    		}
    		var d = pc.getInitDataByDataName(table,'cacheName','init');
    		if($defined(d)){
    			d = d.data;
    		}
    		var result = $cache.query(d,sql, table);
    		var temp = [];
    			if(backFunc){
//    				for(var i = 0 ; temp &&  i < temp.length; i++){
    				var rt = (backFunc)(result);
    				if($chk(rt)){
    					temp = rt;
    				}
    			}else{
    				temp = result;
    			}
    			this.cacheFilterData(temp,table);
    	}
    }
    ,treeDataFilter:function(sqlObj, treeType,treeName,cName,backFunc) {
    	if($chk(sqlObj)) {
    		var sql = "";
    		var table = sqlObj.T;
    		if(sqlObj.W) {
    			sql += "SELECT T.* FROM " + table + " AS T WHERE "+sqlObj.W;
    		}
    		var d = pc.getInitDataByDataName(table,'cacheName','init');
    		if($defined(d)){
    			d = d.data;
    		}
    		var result = $cache.query(d,sql, table);
    		var temp = [];
    			if(backFunc){
//    				for(var i = 0 ; temp &&  i < temp.length; i++){
    				var rt = (backFunc)(result);
    				if($chk(rt)){
    					temp = rt;
    				}
//    					if((backFunc)(result)){
//    					}
//    				}
    			}else{
    				temp = result;
    			}
    			var tempdata = {
    					"data":temp,
    					"name":treeName,
    					 'sword': 'SwordTree'
    				};
    		if(treeType == "tree"){
    			$w(treeName).reloadTree(tempdata);
    		}else{
    			pc.getWidget(cName+"."+treeName).reloadTree(tempdata);
    		}
    		this.cacheFilterData(temp,table);
    	}
    }
    ,cacheFilterData:function(data,table){
    	var tempdata = $H({
			"data":[{
				"data":data,
				cacheName:table
			}]
		});
		
    	if(!$chk(pc.initData)){
    		pc.initData = tempdata;
    	}else{
    		var tdata = pc.initData.data;
    		var tl = tdata.length;
    		var zxtag = false;
    		for(var i = 0; i < tl; i++){
    			var item = tdata[i];
    			var wn = item.cacheName;
    			if($chk(wn) && wn == table){
    				var tag = item.init;
    				if(!$chk(tag)){
    					item.data=data;
    					zxtag = true;
    					break;
    				}
    			}
    		}
    		if(!zxtag){
    			pc.initData.data.extend(tempdata.data);
    		}
    	}
    },
    getTopCacheData:function(name){
    	var tData = top.pc.cacheData;
    	if(tData){
    		var data = tData.data;
    		var result = null;
       	 for(var i=0; i<data.length;i++ ){
    	    	 if(data[i].cache==name){
    	    		 result = data[i];
    	    		 break;
    	    	 }
    	     }
    	    return result;
    	}else return null;
    }

});
var pageContainer,pc;
function swordGetEdit() {
	var location = "" + window.location;
    var edit = (location.indexOf("edit=true") != -1);
    if(edit) {
        return edit;
    }
    var imObj = document.getElementsByTagName("script")[0];
    if(imObj.src.lastIndexOf("Sword.js") < 0) {
//        logger.warn('没有找到sword.js节点，无法初始化编辑模式。。请保证sword.js是页面的第一个js结点');
        return false;
    } else {
        return imObj.getAttribute('edit') == 'true';
    }
}
function $init_Gt(){
	if(window.top.setClientMonitorValue&&window.top.SwordClientTiming)jsR.config.SwordClientTiming = true;
    var edit = swordGetEdit();
    pc = pageContainer = new PageContainer(edit);
    pc.getSelect(); //为了初始化全局click事件
    pc.getMask();
    pc.process();
    MaskDialog.hide();
}
function initSwordPage() {
	try{
		if(parent&&parent.document.getElementById("ym-window")){
	            var n = window.frameElement.name;
	            window.box = window.frameElement.parentNode.ownerDocument.window[n];
		}
	}catch(e){}
    
    if (jsR.config.SwordClientCache&&$defined(window.$cache) && jsR.server()){
    	if(top == self){
    		var cacheInstance =  $cache.getswordcacheInstance();
            var i = 1;
            (function(){
                i++;
                if(cacheInstance.ready){
                	top.$swfcacheobject = getCacheObj();
                    $init_Gt();
                }else{
                    if(i>5){
                        alert("cache swf not init !!!!");
                        return;
                    }
                    setTimeout(arguments.callee,20);
                }

            })();
    	}else {$init_Gt();}
    }else{
        $init_Gt();
    }
    
    $l.log('init');
    $l.flush();
}

function unloadSword() {
    $$('iframe').set('src', '');
}
if(Browser.Engine.trident) {
    window.attachEvent("onload", initSwordPage);
} else {
    window.addEvent('domready', initSwordPage);
}
function _TIMEOUT() {
    if(window.top._SOWRDTIMEOUT) {
        window.top._SOWRDTIMEOUT();
    }
}

